package li.teng.android.xplanet;


import li.teng.android.xplanet.content.MyPositionHelper;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.Toast;



public class MyPlanet extends TabActivity implements OnTouchListener,
OnSharedPreferenceChangeListener{
	private SharedPreferences sharedPreferences;
	XPlanetClient client ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
		final Resources res = getResources();
	    final TabHost tabHost = getTabHost();
	    tabHost.addTab(tabHost.newTabSpec("map")
	        .setIndicator("Map", res.getDrawable(
	            android.R.drawable.ic_menu_mapmode))
	        .setContent(new Intent(this, PositionMap.class)));
	    
	    tabHost.addTab(tabHost.newTabSpec("wiki")
	        .setIndicator("Stats", res.getDrawable(R.drawable.icon))
	        .setContent(new Intent(this, PositionWiki.class)));

	    
	    tabHost.getTabWidget().setVisibility(View.GONE);

	    RelativeLayout layout = new RelativeLayout(this);
	    LayoutParams params =
	        new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
	    layout.setLayoutParams(params);

	    tabHost.addView(layout);
	    layout.setOnTouchListener(this);
	    
	    VoiceGuide.getInstance(this);
	    VoiceGuide.getInstance(this).Init();
	    
	    sharedPreferences.registerOnSharedPreferenceChangeListener(this);
	}


	@Override
	public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return true;
	}
	
    static final private int SETTINGS = Menu.FIRST;
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
	
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
	    super.onPrepareOptionsMenu(menu);
	    boolean map_visable = (getTabHost().getCurrentTabTag() == "map");
        menu.findItem(R.id.menu_show_map)
		.setEnabled(!map_visable)
		.setVisible(!map_visable);
        menu.findItem(R.id.menu_show_wiki)
		.setEnabled(map_visable)
		.setVisible(map_visable);
	    return true;
    }	  
    
	public boolean onOptionsItemSelected(MenuItem item) {  
		Log.d(XplanetConstants.TAG, "MyPlanet.onOptionsItemSelected");
        super.onContextItemSelected(item);
	    switch (item.getItemId()) {
	      case (R.id.menu_settings): {
	          Intent startIntent = new Intent(this, MyTracksSettings.class);
	          this.startActivity(startIntent);
	        return true;
	      }
	      case (R.id.menu_show_map): {
	    	  getTabHost().setCurrentTab(0);
	        return true;
	      }
	      case (R.id.menu_show_wiki): {
	    	  getTabHost().setCurrentTab(1);
	        return true;
	      }	  
	      case (R.id.menu_list_positions): {
	    	  PositionList.m_InitLocation = PositionMap.m_CurruntLocation;
	    	  //Log.d(XplanetConstants.TAG, "start list positions:" + PositionMap.m_CurruntLocation.getLongitude());
	          Intent startIntent = new Intent(this, PositionList.class);
	  	      startActivityForResult(startIntent, XplanetConstants.SHOW_LIST);
	        return true;
	      }
	      case (R.id.menu_report_location): {
	    	  Location location = getCurrentLocation();
	    	  if(location == null)return true;
	    	  if(client == null){
		  	    SimInfo sim = new SimInfo(this);
			    sim.ReadSim();
			    client = new XPlanetClient(sim.simSerialNumber);
	    	  }
	    	  client.ReportPosition(location);
	        return true;
	      }
	      case (R.id.menu_register): {
	    	  if(client == null){
			  	    SimInfo sim = new SimInfo(this);
				    sim.ReadSim();
				    client = new XPlanetClient(sim.simSerialNumber);
	    	  }
	    	  client.registerClient("teng");	    	  
	      }
	    }      
	    return false;
    }
	
	 @Override
	  public void onActivityResult(int requestCode, int resultCode,
	      final Intent results) {
		 switch (requestCode) {
	      case XplanetConstants.SHOW_LIST: {
	          if (results!= null && results.hasExtra("position_id")) {
	        	  Log.d(XplanetConstants.TAG, "try to catch trackId");
	        	  final long trackId = results.getLongExtra("position_id", -1);
	              Log.d(XplanetConstants.TAG, "position_id selected = " + trackId);
	              setSelectedLocation(trackId);
	          }
	      }
		 }
	 }
	 
	  public void setSelectedLocation(final long trackId) {
		    runOnUiThread(new Runnable() {
		      public void run() {
		        SharedPreferences.Editor editor = sharedPreferences.edit();
		        editor.putLong(getString(R.string.selected_track_key), trackId);
		        Log.d(XplanetConstants.TAG, "setSelectedLocation" + trackId);
		        editor.commit();
		      }
		    });
	}
	  
	  public Location getCurrentLocation() {
		    // TODO: Let's look at more advanced algorithms to determine the best
		    // current location.
		    LocationManager locationManager =
		        (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		    if (locationManager == null) {
		      return null;
		    }
		    final long maxAgeMilliSeconds = 1000 * 60 * 1;  // 1 minute
		    final long maxAgeNetworkMilliSeconds = 1000 * 60 * 10;  // 10 minutes
		    final long now = System.currentTimeMillis();
		    Location loc = locationManager.getLastKnownLocation(
		    		XplanetConstants.GPS_PROVIDER);
		    if (loc == null || loc.getTime() < now - maxAgeMilliSeconds) {
		      // We don't have a recent GPS fix, just use cell towers if available
		      loc = locationManager.getLastKnownLocation(
		          LocationManager.NETWORK_PROVIDER);
		      if (loc == null || loc.getTime() < now - maxAgeNetworkMilliSeconds) {
		        // We don't have a recent cell tower location, let the user know:
		        Toast.makeText(this, "We don't have a recent cell tower location",Toast.LENGTH_LONG).show();
		        return null;
		      } else {
		       // Let the user know we have only an approximate location:
		       Toast.makeText(this, "only an approximate location",Toast.LENGTH_LONG).show();
		      }
		    }
		    return loc;
		  }

}
